//
//  CalendarView.swift
//  KoiAccounting
//
//  Created by 纪洪文 on 27.03.25.
//

import SwiftUI

// MARK: - 日历数据模型
struct CalendarDate: Identifiable {
    let id = UUID()
    let date: Date
    let isCurrentMonth: Bool
    var isSelected: Bool
    var hasEvent: Bool
}

// MARK: - 日历 ViewModel
class CalendarViewModel: ObservableObject {
    @Published var selectedDate: Date = Date()
    @Published var calendarDates: [CalendarDate] = []
    @Published var currentMonth: Date = Date()
    
    private let calendar: Calendar = {
        var calendar = Calendar.current
        // 设置每周第一天为周一
        calendar.firstWeekday = 2
        return calendar
    }()
    
    private let dateFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy年MM月"
        return formatter
    }()
    
    init(initialDate:Date = Date()) {
        currentMonth = initialDate
        selectedDate = initialDate
        generateDates()
    }
    
    var currentMonthString: String {
        dateFormatter.string(from: currentMonth)
    }
    
    func moveMonth(by value: Int) {
        if let newDate = calendar.date(byAdding: .month, value: value, to: currentMonth) {
            currentMonth = newDate
            generateDates()
        }
    }
    
    private func generateDates() {
        calendarDates = []
        
        // 获取当月第一天
        let components = calendar.dateComponents([.year, .month], from: currentMonth)
        guard let firstDayOfMonth = calendar.date(from: components) else { return }
        
        // 获取当月天数
        let daysInMonth = calendar.range(of: .day, in: .month, for: currentMonth)?.count ?? 0
        
        // 获取第一天是周几
        let firstWeekday = calendar.component(.weekday, from: firstDayOfMonth)
        let offsetDays = firstWeekday - calendar.firstWeekday
        
        // 添加上月的日期
        if offsetDays > 0 {
            for day in (1...offsetDays).reversed() {
                if let date = calendar.date(byAdding: .day, value: -day, to: firstDayOfMonth) {
                    calendarDates.append(CalendarDate(date: date, isCurrentMonth: false, isSelected: false, hasEvent: false))
                }
            }
        }
        
        // 添加当月的日期
        for day in 1...daysInMonth {
            if let date = calendar.date(byAdding: .day, value: day - 1, to: firstDayOfMonth) {
                calendarDates.append(CalendarDate(date: date, isCurrentMonth: true, isSelected: calendar.isDate(date, inSameDayAs: selectedDate), hasEvent: false))
            }
        }
        
        // 添加下月的日期来填充最后一周
        let remainingDays = 42 - calendarDates.count // 6周 * 7天
        if remainingDays > 0 {
            for day in 1...remainingDays {
                if let date = calendar.date(byAdding: .day, value: day, to: calendar.date(byAdding: .day, value: daysInMonth - 1, to: firstDayOfMonth) ?? Date()) {
                    calendarDates.append(CalendarDate(date: date, isCurrentMonth: false, isSelected: false, hasEvent: false))
                }
            }
        }
    }
    
    func setCurrentDate (_ date:Date) {
        currentMonth = date
        selectedDate = date
        generateDates()
    }
    
    func selectDate(_ date: Date) {
        selectedDate = date
        generateDates()
    }
}

// MARK: - 日历视图
struct CalendarView: View {
    
    @Environment(\.presentationMode) var presentationMode
    
    @StateObject private var viewModel: CalendarViewModel
    @Binding var selectedDate: Date
    // 添加日期选择回调
    var onDateSelected: ((Date) -> Void)?
    
    private let weekDays = ["一", "二", "三", "四", "五", "六", "日"]
    private let columns: [GridItem] = Array(repeating: .init(.flexible()), count: 7)
    
    init(selectedDate: Binding<Date>, onDateSelected: ((Date) -> Void)? = nil) {
        self._selectedDate = selectedDate
        _viewModel = StateObject(wrappedValue: CalendarViewModel(initialDate: selectedDate.wrappedValue))
        self.onDateSelected = onDateSelected
    }
    
    var body: some View {
        VStack(spacing: 20) {
            // 月份选择器
            HStack {
                Button(action:{
                    viewModel.setCurrentDate(Date())
                }) {
                    Text("返回今天")
                        .font(.system(size: 13))
                        .foregroundColor(Color.koiColorTitleSecond)
                }

                Spacer()
                
                Button(action: { viewModel.moveMonth(by: -1) }) {
                    ZStack {
                        Color.koiColorBackgroundItem
                            .frame(width: 28,height: 28)
                            .cornerRadius(50)
                        Image("koi_ic_arrow_left")
                    }
                }
                
                // Spacer()
                
                Text(viewModel.currentMonthString)
                    .font(.system(size: 13))
                    .foregroundColor(Color.koiColorTextMain)
                    .padding(EdgeInsets(top: 0, leading: 8, bottom: 0, trailing: 8))
                
                // Spacer()
                
                Button(action: { viewModel.moveMonth(by: 1) }) {
                    ZStack {
                        Color.koiColorBackgroundItem
                            .frame(width: 28,height: 28)
                            .cornerRadius(50)
                        Image("koi_ic_arrow_right")
                    }
                }
                
                Spacer()
                
                Button(action: {
                    onDateSelected?(viewModel.selectedDate)
                    presentationMode.wrappedValue.dismiss()
                }) {
                    Text("确定")
                        .font(.system(size: 15))
                        .bold()
                        .foregroundColor(Color.koiColorPrimary)
                }
            }
            .padding(.horizontal)
            
            // 星期头部
            HStack {
                ForEach(weekDays, id: \.self) { day in
                    Text(day)
                        .font(.system(size: 14))
                        .foregroundColor(Color.koiColorTitleSecond)
                        .frame(maxWidth: .infinity)
                        .foregroundColor(.secondary)
                }
            }
            
            // 日期网格
            LazyVGrid(columns: columns, spacing: 8) {
                ForEach(viewModel.calendarDates) { calendarDate in
                    DateCell(date: calendarDate)
                        .onTapGesture {
                            viewModel.selectDate(calendarDate.date)
                            // 点击确定再选中日期
                            // onDateSelected?(calendarDate.date)
                        }
                }
            }
        }
        .padding()
        .onChange(of: selectedDate) { newDate in
            // 当外部更新选中日期时同步更新 ViewModel
            viewModel.setCurrentDate(newDate)
        }
        .onChange(of: viewModel.selectedDate) { newDate in
            // 当 ViewModel 更新选中日期时同步更新外部绑定的日期
            // 不与外界同步，点击确定再同步
            // selectedDate = newDate
        }
    }
}

// MARK: - 日期单元格
struct DateCell: View {
    let date: CalendarDate
    private let calendar = Calendar.current
    private let cellSize = CGFloat(25)
    
    var body: some View {
        ZStack {
            Circle()
                .fill(date.isSelected ? Color.koiColorPrimary : Color.clear)
                .frame(width: cellSize, height: cellSize)
            
            Text("\(calendar.component(.day, from: date.date))")
                .font(.system(size: 14))
                .foregroundColor(cellTextColor)
                .frame(width: cellSize, height: cellSize)
            
            if date.hasEvent {
                Circle()
                    .fill(Color.blue)
                    .frame(width: 6, height: 6)
                    .offset(y: 12)
            }
        }
    }
    
    private var cellTextColor: Color {
        if date.isSelected {
            return .white
        }
        return date.isCurrentMonth ? Color.koiColorTitle : .secondary
    }
}

// MARK: - 带事件的扩展版本
struct CalendarEventView: View {
    @Binding var selectedDate: Date
    @StateObject private var viewModel = CalendarViewModel()
    @State private var showingEventSheet = false
    @State private var selectedEvent: Event?
    
    var body: some View {
        VStack {
            CalendarView(selectedDate: $selectedDate) { date in
                
            }
            
            // 事件列表
            List {
                // 这里显示选中日期的事件
                Text("选中日期：\(viewModel.selectedDate, style: .date)")
            }
        }
        .sheet(item: $selectedEvent) { event in
            EventDetailView(event: event)
        }
    }
}

// MARK: - 事件模型
struct Event: Identifiable {
    let id = UUID()
    var title: String
    var date: Date
    var notes: String?
}

// MARK: - 事件详情视图
struct EventDetailView: View {
    let event: Event
    
    var body: some View {
        VStack {
            Text(event.title)
                .font(.title)
            Text(event.date, style: .date)
            if let notes = event.notes {
                Text(notes)
            }
        }
        .padding()
    }
}

@available(iOS 18.0, *)
#Preview {
    @Previewable @State var date = Date()
    CalendarView(selectedDate: $date) { selectedDate in }
}
